const app = require('express').Router();
const multer = require('multer')
const fs = require('fs'); // 引入fs模块
const qiniuUpload = require("../service/fileUpload");
const path = require('path');
const upload = multer({ dest: "./uploads" });

app.post('/fileUpload', upload.array('file', 20), async function (req, res, next) {
  let fileAddress = [];
  try {
    fileAddress = req.files.map(async function (file) {
      const fileOriginalName = file.originalname;
      const fileOriginalNameLen = fileOriginalName.length;
      //后缀名
      const extra = fileOriginalName.slice(fileOriginalName.lastIndexOf("."), fileOriginalNameLen);
      const qiniuRes = await qiniuUpload(file.filename + extra, path.join(__dirname, "../../", file.path));
      return qiniuRes["key"];
    });
    fileAddress = await Promise.all(fileAddress);
    deleteall("./uploads");
    res.json({ status: 200, file: fileAddress.length > 1 ? fileAddress : fileAddress[0] });
  } catch (e) {
    res.json({ status: "error" })
  }
});

function deleteall(path) {
  var files = [];
  if (fs.existsSync(path)) {
    files = fs.readdirSync(path);
    files.forEach(function (file, index) {
      var curPath = path + "/" + file;
      if (fs.statSync(curPath).isDirectory()) { // recurse
        deleteall(curPath);
      } else { // delete file
        fs.unlinkSync(curPath);
      }
    });
  }
};

module.exports = app;
